package com.guokai2012.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @Author guokai2012
 */
public class MyMenBar extends JMenuBar {
    private final JFrame frame;
    private JDialog dialog;
    private PropertiesManager proManager;

    public MyMenBar(JFrame frame) {
        this.frame = frame;
    }

    public void initMenBar(PropertiesManager properties) {
        this.proManager = properties;
        JMenu menu = new JMenu("设置");
        add(menu);
        JMenuItem item = new JMenuItem("七牛云设置");
        menu.add(item);
        item.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                dialog.setVisible(true);
            }
        });
        showSetPanel();
    }

    /**
     * 绘制弹出框 主界面
     */
    private void showSetPanel() {
        this.dialog = new JDialog(frame, "七牛云存储设置");
        dialog.setSize(400, 340);
        // 设置为 没有 关闭按钮
        // this.dialog.setUndecorated(true);
        dialog.setLocationRelativeTo(frame);
        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        Object[] protest = new Object[]{
                proManager.getAk(),
                proManager.getSk(),
                proManager.getBucket(),
                proManager.getDownUrl(),
                proManager.getUpStep(),
                proManager.getSpace(),
                proManager.getBlobIo()
        };

        JTextField[] textFields = new JTextField[7];
        for (int i = 0; i < textFields.length; i++) {
            JTextField field = new JTextField();
            field.setText(String.valueOf(protest[i]));
            textFields[i] = field;
        }
        JLabel[] labels = new JLabel[]{
                new JLabel("AK："),
                new JLabel("SK："),
                new JLabel("BUCKET："),
                new JLabel("文件下载域名："),
                new JLabel("上传间隔(分钟)："),
                new JLabel("最大存储空间(MB)："),
                new JLabel("最大下行流量(MB)：")
        };
        addLabelTextRows(labels, textFields, panel);

        JButton sbt = new JButton("保存");
        sbt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String url = textFields[3].getText();
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    showError("【文件下载域名】请以http:// 或 https:// 开头");
                    return;
                }
                int upStep = 0;
                try {
                    upStep = Integer.parseInt(textFields[4].getText());
                    if (upStep < 10) {
                        showError("【上传间隔(分钟)】请设置10分钟以上！");
                        return;
                    }
                } catch (NumberFormatException ex) {
                    showError("【上传间隔(分钟)】值输入错误，请输入正确的数字");
                    return;
                }
                double space = 0, blobIo = 0;
                try {
                    space = Double.parseDouble(textFields[5].getText());
                } catch (NumberFormatException ex) {
                    showError("【最大存储空间(MB)】值输入错误，请输入正确的数字");
                    return;
                }
                try {
                    blobIo = Double.parseDouble(textFields[6].getText());
                } catch (NumberFormatException ex) {
                    showError("【最大下行流量(MB)】值输入错误，请输入正确的数字");
                    return;
                }
                proManager.setAk(textFields[0].getText());
                proManager.setSk(textFields[1].getText());
                proManager.setBucket(textFields[2].getText());
                proManager.setDownUrl(url);
                proManager.setUpStep(upStep);
                proManager.setSpace(space);
                proManager.setBlobIo(blobIo);
                proManager.storeProperties();
                dialog.setVisible(false);

                int commit = commit("设置成功，重启立即生效。是否重启？\nTip：重启请手动运行【start.vbs】文件");
                if (commit == JOptionPane.YES_OPTION) {
                    if (frame instanceof MainFrame) {
                        System.out.println("七牛云OSS设置，程序重启结果：" + ((MainFrame) frame).reBoot());
                    }
                    System.exit(0);
                } else {
                    System.out.println("七牛云OSS设置，但未重启");
                }
            }
        });
        JButton cbt = new JButton("取消");
        cbt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
            }
        });
        JPanel btnPanel = new JPanel();
        btnPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        btnPanel.add(sbt);
        btnPanel.add(cbt);

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(10, 10, 10, 10);
        c.anchor = GridBagConstraints.EAST;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.NONE;
        panel.add(btnPanel, c);
        dialog.add(panel);
    }

    /**
     * 添加 输入行
     */
    private void addLabelTextRows(JLabel[] labels, JTextField[] textFields, Container container) {
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 10, 5, 10);
        c.anchor = GridBagConstraints.EAST;
        int numLabels = labels.length;
        for (int i = 0; i < numLabels; i++) {
            //next-to-last
            c.gridwidth = GridBagConstraints.RELATIVE;
            //reset to default
            c.fill = GridBagConstraints.NONE;
            //reset to default
            c.weightx = 0.0;
            container.add(labels[i], c);
            //end row
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 1.0;
            container.add(textFields[i], c);
        }
    }

    /**
     * 显示错误提示
     */
    private void showError(String mess) {
        JOptionPane.showMessageDialog(frame, mess, "错误提示！", JOptionPane.ERROR_MESSAGE);
    }

    private int commit(String mess) {
        return JOptionPane.showConfirmDialog(frame, mess, "信息确认", JOptionPane.YES_NO_OPTION);
    }
}
